#!/bin/bash - 
#
#  Usage:     Exercising the 'date' command
#  Author:    bucunzai <freecityer@gmail.com>
#  Version:   1.0
#  Created:   03/06/2011 10:53:59 PM CST
#

set -o nounset                              # Treat unset variables as an error

echo "The number of days since the year's beginning is `date +%j`."
# %j gives day of year.

echo "The number of seconds elapsed since 01/01/1970 is `date +%s`."
# %s gives seconds since "UNIX epoch" began"

# creat "random" temp filename
#prefix=temp
#suffix=$(date +%s)
#filename=$prefix.suffix
#echo "Temporary filename = $filename"

MPHR=60 # mins per hour.
HPD=24 # hours per day.

diff () {
    printf '%s' $(( $(date -u -d"$TARGET" +%s) - $(date -u -d"$CURRENT" +%s) ))
    # %d = day of month
}

CURRENT=$(date -u -d '2007-09-01 17:30:00' '+%F %T.%N %Z')
TARGET=$(date -u -d'2007-12-25 12:30:00' '+%F %T.%N %Z')
# %F= full date, %T = %H:%M:%S, %N = nanoseconds, %Z = time zone.

printf '\nIn 2007, %s ' "$(date -d"$CURRENT + $(( $(diff) / $MPHR / $MPHR / $HPD /2 )) days" '+%d %B')"
# %B = name of month
printf 'was halfway between %s ' "$(date -d"$CURRENT" '+%d %B')"
printf 'and %s\n' "$(date -d"$TARGET" '+%d %B')"

# copy the code below
printf '\nOn %s at %s, there were\n' \
        $(date -u -d"$CURRENT" +%F) $(date -u -d"$CURRENT" +%T)
DAYS=$(( $(diff) / $MPHR / $MPHR / $HPD ))
CURRENT=$(date -d"$CURRENT +$DAYS days" '+%F %T.%N %Z')
HOURS=$(( $(diff) / $MPHR / $MPHR ))
CURRENT=$(date -d"$CURRENT +$HOURS hours" '+%F %T.%N %Z')
MINUTES=$(( $(diff) / $MPHR ))
CURRENT=$(date -d"$CURRENT +$MINUTES minutes" '+%F %T.%N %Z')
printf '%s days, %s hours, ' "$DAYS" "$HOURS"
printf '%s minutes, and %s seconds ' "$MINUTES" "$(diff)"
printf 'until Christmas Dinner!\n\n'

exit 0
